import React, { Component } from 'react';

class Child2 extends Component {
  state = {
    color: '',
    propsColor: ''
  }

  constructor() {
    super()
    console.log('constructor')
  }

  static getDerivedStateFromProps(props, state) {
    // 返回值：和state进行合并（merge）
    // 此方法不能访问this
    
    // if (props.color === state.propsColor) {
    //   return {
    //     color: state.color,
    //     propsColor: state.color
    //   }
    // } else {
    //   return {
    //     color: props.color,
    //     // 保存上一次props的值
    //     propsColor: props.color
    //   }
    // }

    return props.color === state.propsColor
      ? { color: state.color, propsColor: state.color }
      : { color: props.color, propsColor: props.color}
  }

  handleClick = () => {
    this.setState({
      color: 'green'
    })
  }

  handleClick2 = () => {
    this.forceUpdate()
  }

  handleChangeColor = () => {
    this.setState({
      color: 'yellow'
    })
  }

  render() {
    return (
      <div>
        <span style={{color: this.state.color}}>hello</span>
        <button onClick={this.handleClick}>click</button>
        <button onClick={this.handleClick2}>forceUpdate</button>
        <button onClick={this.handleChangeColor}>change color</button>
      </div>
    );
  }
}

export default Child2;